package com.jtlrm.ckd.mvp.view.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;

import com.base.sdk.base.net.CommonObserver;
import com.base.sdk.util.EditInputFilter;
import com.jtlrm.ckd.R;
import com.jtlrm.ckd.base.acitvity.TitleBarActivity;
import com.jtlrm.ckd.entity.YingYangDetailData;
import com.jtlrm.ckd.entity.event.YinShiUpdateMessage;
import com.jtlrm.ckd.entity.event.YingYangUpdateMessage;
import com.jtlrm.ckd.mvp.model.YinYangModel;
import com.jtlrm.ckd.util.EventBusUtil;

import java.text.DecimalFormat;

import butterknife.BindView;

public class YingYangPingGuDetailActivity extends TitleBarActivity {

    @BindView(R.id.shengao)
    EditText shenGaoT;
    @BindView(R.id.tizhong)
    EditText tiZhongT;
    @BindView(R.id.bmi)
    EditText bmiT;
    @BindView(R.id.shang_bi_wei)
    EditText shangBiWeiT;
    @BindView(R.id.gong_san_tou_ji)
    EditText gongSanTouJiT;
    @BindView(R.id.zuo_shou)
    EditText zuoShouT;
    @BindView(R.id.you_shou)
    EditText youShouT;
    @BindView(R.id.shu_zhang_ya)
    EditText shuZhangYaT;
    @BindView(R.id.shou_suo_ya)
    EditText shouSuoYaT;
    YingYangDetailData submitData;
    YinYangModel yinYangModel;

    YingYangDetailData personData;
    boolean isAdd = false; // 是否是新增数据
    String patientId;

    public static void goDetail(Context context, boolean isAdd
            , String patientId, YingYangDetailData detailData) {
        Intent intent = new Intent(context, YingYangPingGuDetailActivity.class);
        intent.putExtra("isAdd", isAdd);
        intent.putExtra("patientId", patientId);
        intent.putExtra("detailData", detailData);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        isAdd = intent.getBooleanExtra("isAdd", false);
        patientId = intent.getStringExtra("patientId");
        personData = (YingYangDetailData) intent.getSerializableExtra("detailData");
        super.onCreate(savedInstanceState);
    }

    @Override
    protected String getTitleText() {
        if (isAdd) {
            return "新增营养评估";
        } else if (personData == null) {
            return "编辑营养评估";
        } else {
            return "营养评估";
        }
    }

    @Override
    protected void setContentLayout() {
        setContentView(R.layout.activity_ying_yang_ping_gu_detail);
    }

    @Override
    protected void initView() {
        submitData = new YingYangDetailData();
        yinYangModel = new YinYangModel();
        bmiT.setEnabled(false);
    }

    @Override
    protected void obtainData() {
        if (!isAdd) {
            if (personData == null) {
                // 如果没有个人数据，则表示是编辑数据，需要查询最新数据
                queryToDayDetail();
                setIsEdit(true);

            } else {
                // 如果有数据表示，不能编辑数据
                setContent(personData);
                setIsEdit(false);
            }
        } else {
            setIsEdit(true);
        }
    }

    private void queryToDayDetail() {
        yinYangModel.queryToDayDetail(patientId, new CommonObserver<YingYangDetailData>() {
            @Override
            public void onError(int errType, String errMessage) {
                showToast(errMessage);
            }

            @Override
            public void onResult(YingYangDetailData data) {
                setContent(data);
            }
        }, lifecycleSubject);
    }

    private void setContent(YingYangDetailData data) {
        setText(shenGaoT, data.getpHeight());
        setText(tiZhongT, data.getpWeight());
        setText(bmiT, data.getBim());
        setText(shangBiWeiT, data.getUpperArm());
        setText(gongSanTouJiT, data.getTricepsBrachii());
        setText(zuoShouT, data.getLeftGrip());
        setText(youShouT, data.getRightGrip());
        setText(shouSuoYaT, data.getHighBlood());
        setText(shuZhangYaT, data.getLowBlood());
    }

    @Override
    protected void initEvent() {
        if (isAdd || personData == null) {
           // InputFilter[] filters = {new EditInputFilter(context)};
//            shenGaoT.setFilters(filters);
//            tiZhongT.setFilters(filters);
//            shangBiWeiT.setFilters(filters);
//            gongSanTouJiT.setFilters(filters);
//            zuoShouT.setFilters(filters);
//            youShouT.setFilters(filters);
//            shuZhangYaT.setFilters(filters);
//            shouSuoYaT.setFilters(filters);
            tiZhongT.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    updateBMI();
                }
            });
            shenGaoT.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    updateBMI();
                }
            });
        }
    }

    private void updateBMI() {
        String shen = getTextStr(shenGaoT);
        String tiZhong = getTextStr(tiZhongT);
        if (notEmpty(shen) && notEmpty(tiZhong)) {
            try {
                Double s = Double.parseDouble(shen) / 100;
                Double t = Double.parseDouble(tiZhong);
                Double b = t / (s * s);
                setText(bmiT, new DecimalFormat("0.00").format(b));
            } catch (Exception e) {
            }

        }
    }

    @Override
    protected void initTitleBar() {
        super.initTitleBar();
        if (isAdd || personData == null) {
            titleBar.tvRight.setText("完成提交");
            titleBar.tvRight.setVisibility(View.VISIBLE);
            titleBar.tvRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!isAdd) {
                        if (personData == null) {
                            // 如果没有个人数据，则表示是编辑数据，需要查询最新数据
                            updateData();
                        }
                    } else {
                        submit();
                    }
                }
            });
        }
    }

    private void updateData() {
        if (!validate()) {
            return;
        }
        showLoadingDialog("更新中");
        yinYangModel.updateYingYangData(submitData, new CommonObserver<YingYangDetailData>() {
            @Override
            public void onError(int errType, String errMessage) {
                dismissLoadingDialog();
                showToast(errMessage);
            }

            @Override
            public void onResult(YingYangDetailData data) {
                EventBusUtil.postEvent(new YingYangUpdateMessage());
                dismissLoadingDialog();
                showToast("更新成功");
                finish();
            }
        }, lifecycleSubject);
    }

    private void submit() {
        if (!validate()) {
            return;
        }
        showLoadingDialog("提交中");
        yinYangModel.addYingYangData(submitData, new CommonObserver<YingYangDetailData>() {
            @Override
            public void onError(int errType, String errMessage) {
                dismissLoadingDialog();
                showToast(errMessage);
            }

            @Override
            public void onResult(YingYangDetailData data) {
                EventBusUtil.postEvent(new YingYangUpdateMessage());
                dismissLoadingDialog();
                showToast("提交成功");
                finish();
            }
        }, lifecycleSubject);
    }

    private boolean validate() {
//        if (inputEmpty(shenGaoT)) {
//            showToast("请填写身高");
//            return false;
//        }
//        if (inputEmpty(tiZhongT)) {
//            showToast("请填写体重");
//            return false;
//        }
//        if (inputEmpty(bmiT)) {
//            showToast("请填写BMI");
//            return false;
//        }
//        if (inputEmpty(shangBiWeiT)) {
//            showToast("请填写上臂围");
//            return false;
//        }
//        if (inputEmpty(gongSanTouJiT)) {
//            showToast("请填写肱三头肌皮褶厚度");
//            return false;
//        }
//        if (inputEmpty(zuoShouT)) {
//            showToast("请填写左手握力");
//            return false;
//        }
//        if (inputEmpty(youShouT)) {
//            showToast("请填写右手握力");
//            return false;
//        }
//        if (inputEmpty(shuZhangYaT)) {
//            showToast("请填写舒张压");
//            return false;
//        }
//        if (inputEmpty(shouSuoYaT)) {
//            showToast("请填写收缩压");
//            return false;
//        }
        if (inputEmpty(shenGaoT) && inputEmpty(tiZhongT) && inputEmpty(bmiT) && inputEmpty(shangBiWeiT)
                && inputEmpty(gongSanTouJiT) && inputEmpty(zuoShouT) && inputEmpty(youShouT)
                && inputEmpty(shuZhangYaT) && inputEmpty(shouSuoYaT)) {
            showToast("至少填写一项");
            return false;
        }
        if (inputEmpty(shuZhangYaT) != inputEmpty(shouSuoYaT)) {
            showToast("舒张压和收缩压必须同时填写");
            return false;
        }
        submitData.setpHeight(getTextStr(shenGaoT));
        submitData.setpWeight(getTextStr(tiZhongT));
        submitData.setBim(getTextStr(bmiT));
        submitData.setUpperArm(getTextStr(shangBiWeiT));
        submitData.setTricepsBrachii(getTextStr(gongSanTouJiT));
        submitData.setLeftGrip(getTextStr(zuoShouT));
        submitData.setRightGrip(getTextStr(youShouT));
        submitData.setHighBlood(getTextStr(shouSuoYaT));
        submitData.setLowBlood(getTextStr(shuZhangYaT));
        submitData.setPatientId(patientId);
        if (isNotRound(0, 500, submitData.getpHeight(), "身高", "cm")) {
            return false;
        }
        if (isNotRound(0, 500, submitData.getpWeight(), "体重", "kg")) {
            return false;
        }
        if (isNotRound(0, 100, submitData.getUpperArm(), "上臂围", "cm")) {
            return false;
        }
        if (isNotRound(0, 100, submitData.getTricepsBrachii(), "肱三头肌皮褶厚度", "cm")) {
            return false;
        }
        if (isNotRound(0, 500, submitData.getLeftGrip(), "左手握力", "kg")) {
            return false;
        }
        if (isNotRound(0, 500, submitData.getRightGrip(), "右手手握力", "kg")) {
            return false;
        }
        if (isNotRound(0, 500, submitData.getHighBlood(), "收缩压", "mmHg")) {
            return false;
        }
        if (isNotRound(0, 500, submitData.getLowBlood(), "舒张压", "mmHg")) {
            return false;
        }
        return true;
    }

    /**
     * 判断是否在不在数值范围内
     *
     * @return
     */
    public boolean isNotRound(int min, int max, String value, String label, String danwei) {
        if (!notEmpty(value)) {
            return false;
        }
        Double v = Double.parseDouble(value);
        if (v < min || v > max) {
            showToast(label + "应该在" + min + "~" + max + danwei + "之间");
            return true;
        }
        return false;
    }

    public void setIsEdit(boolean isEdit) {
        shenGaoT.setEnabled(isEdit);
        tiZhongT.setEnabled(isEdit);
        shangBiWeiT.setEnabled(isEdit);
        gongSanTouJiT.setEnabled(isEdit);
        zuoShouT.setEnabled(isEdit);
        youShouT.setEnabled(isEdit);
        shuZhangYaT.setEnabled(isEdit);
        shouSuoYaT.setEnabled(isEdit);
    }
}
